<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 01:21:39
 * @LastEditTime: 2023-10-14 16:16:35
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Traits;

use App\Models\Dic;
use App\Models\Material;
use App\Models\MpcLot;
use App\Models\MpcLocation;
use App\Models\MpcMoisture;
use App\Models\ProColor;
use App\Models\ProColorMy;
use App\Models\Type;

trait MaterialTrait
    {
    use CompanyTrait;
    public function material()
        {
        return $this->belongsTo(Material::class);
        }
    public function glue()
        {
        return $this->belongsTo(Material::class);
        }
    public function unit()
        {
        return $this->belongsTo(Dic::class, "unit_id", "key")->where(function ($q)
            {
            $q->where("code", 'unit');
            });
        }
    public function ounit()
        {
        return $this->belongsTo(Dic::class, "ounit_id", "key")->where(function ($q)
            {
            $q->where("code", 'unit');
            });
        }
    public function type()
        {
        return $this->belongsTo(Type::class);
        }

    public function customer_unit()
        {
        return $this->belongsTo(Dic::class, "customer_unit_id", "key")->where(function ($q)
            {
            $q->where("code", 'unit');
            });
        }
    public function _resetLot()
        {
        $lot_data = MpcLot::where("name", $this->lot_name)
            ->where("company_id", $this->company_id)
            ->where("material_id", $this->material_id)
            ->orderBy("sort", "desc")->first();
        $new_lot  = [
            'material_id' => $this->material_id,
            'name'        => $this->lot_name,
            'company_id'  => $this->company_id,
            'sort'        => 0
        ];
        if ($lot_data) {
            $new_array = $lot_data->toArray();
            $new_array['sort']++;
            unset($new_array['id']);
            $new_lot = array_merge($new_lot, $new_array);
            }
        return MpcLot::create($new_lot)->id;
        }

    public function location()
        {
        return $this->belongsTo(MpcLocation::class);
        }
    public function old_location()
        {
        return $this->belongsTo(MpcLocation::class);
        }

    }